package dq.study.nio.java.buffer;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

/**
 * 从channel读取数据到buffer
 * 从buffer写入数据到channel
 *
 * @author dongqun
 * @date 2020/4/3 9:26
 */
public class ChannelAndBuffer {


    private static byte[] readChannelToBuffer(String path) {
        byte[] result = new byte[0];
        try {
            RandomAccessFile file = new RandomAccessFile(path, "r");
            FileChannel fileChannel = file.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int havenReadCount = fileChannel.read(buffer);
            while (havenReadCount != -1) {
                buffer.flip();
                result = new byte[result.length + havenReadCount];
                int i = 1;
                while (buffer.hasRemaining()) {
                    result[result.length - havenReadCount + i - 1] = buffer.get();
                    i++;
                }
                buffer.clear();
                havenReadCount = fileChannel.read(buffer);
            }
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    private static void writeBufferToChannel(String path) throws IOException {
        RandomAccessFile file = new RandomAccessFile(path, "buffer");
        FileChannel channel = file.getChannel();
        CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
        ByteBuffer buffer = encoder.encode(CharBuffer.wrap("万里长江横渡\r\n极目楚天舒\r\n"));
        channel.write(buffer);
    }


    public static void main(String[] args) throws IOException {
        System.out.println(new String(readChannelToBuffer("C:\\Users\\DELL\\Desktop\\主席诗词.txt")));
//        writeBufferToChannel("C:\\Users\\DELL\\Desktop\\主席诗词.txt");
    }
}
